// pages/oa/logs/write.js
var api = require("../../../utils/api.js");
var util = require('../../../utils/util.js');
var orgid = "";
var userId = "";
var userName = "";
Page({

  /**
   * 页面的初始数据
   */
  data: {
    STdate: ["请选择日期", "请选择日期"],
    detail: false,
    write: true,
    types: "",
    show: false,
    dayShow: false,
    weekShow: false,
    monthShow: false,
    logDetailData: '',
    accountInfosList: [],//抄送人
    userIds: [],//新增加的抄送人
    fileUrlList: [],
    //图片附件
    imgUrls: [],
    listFile: [],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    orgid = wx.getStorageSync('companyId');
    userId = wx.getStorageSync('userId');
    userName = wx.getStorageSync('name');
    wx.setNavigationBarTitle({
      title: "写日志"
    });
    // var id = options.id;
    // var flag = options.flag;
    // var currentTab = options.currentTab;
    // if (id != null){

    // }
    // wx.request({
    //   url: getApp().data.servsers + "/logManageForMobile/queryMyWorkLogById.shtml",
    //   data: {
    //     id: id,
    //   },
    //   header: {
    //     'content-type': 'application/json' // 默认值
    //   },
    //   success: function (res) {
    //     if (res.data.code == 200) {
    //       console.log(res.data);
    //       var logDetailData = res.data.data;
    //       that.setData({
    //         logDetailData: logDetailData,
    //       })
    //     }
    //   }
    // })
  },
  /**删除附件 */
  deleteFile: function (e) {
    var that = this;
    var id = e.currentTarget.dataset.id;
    var index = e.currentTarget.dataset.index;
    wx.showModal({
      title: '提示',
      content: '确定要删除吗？',
      success: function (sm) {
        if (sm.confirm) {
          api.fetchApi2("logManage/deleteFileByIdForMobile?id=" + id, {
          }, "POST").then(res => {
            if (res.data.code == 200) {
              var fileUrlList = that.data.fileUrlList;
              var imgUrls = that.data.imgUrls;
              var listFile = that.data.listFile;
              fileUrlList.splice(index, 1)
              imgUrls.splice(index, 1);
              listFile.splice(index, 1);
              that.setData({
                fileUrlList: fileUrlList,
                imgUrls: imgUrls,
                listFile: listFile,

              });
              setTimeout(function () {
                util.showMsg("删除成功", 1, 'none');
              }, 1000);
            } else {
              util.showMsg(res.data.msg, 1, 'none');
            }
          });
        }
        else if (sm.cancel) {
          console.log('用户点击取消')
        }
      }
    })


  },
  /**
   * 上传附件
   */
  upLoad: function (e) {
    var that = this;
    wx.chooseImage({
      count: 9, // 默认9
      sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        console.log(res);
        var tempFilePaths = res.tempFilePaths; // 返回选定照片的本地ID列表，tempFilePaths可以作为img标签的src属性显示图片
        var size = tempFilePaths.length;
        for (var i = 0; i < size; i++) {
          wx.showLoading({
            title: '正在上传',
          });
          const uploadTask = wx.uploadFile({
            url: getApp().data.servsers + "/v1/api/logManage/saveFileForMobile",
            filePath: tempFilePaths[i],
            name: 'file',
            formData: {
              'username': wx.getStorageSync('name'),
              log_id: '',
            },
            header: {
              'token': wx.getStorageSync('token')
            },
            success: function (res) {
              var data = res.data;
              var result = JSON.parse(data);
              var fileUrlListResult = result.data;
              if (result.msg == "success") {
                wx.hideLoading();
                wx.showToast({
                  title: "上传成功",
                  icon: 'none',
                  duration: 1000
                });
                //回显图片
                var list = that.data.fileUrlList;
                var listFile = that.data.listFile;
                list.push(fileUrlListResult);
                listFile.push(fileUrlListResult.id);


                that.setData({
                  fileUrlList: list,
                  listFile: listFile,
                });
              } else {
                if (result.code == 300) {
                  wx.showToast({
                    title: result.msg,
                    icon: "none"
                  });
                  setTimeout(function () {
                    api.logout();// 退出登录
                  }, 1500);
                } else {
                  wx.showToast({
                    title: "上传失败",
                    icon: 'none',
                    duration: 1000
                  });
                }
              }
            }
          })

        }

      }
    });
  },
  //显示图片
  showImg: function (option) {
    var that = this;
    var index = option.currentTarget.dataset.index;
    var fileUrlListResult = that.data.fileUrlList;
    for (var index in fileUrlListResult) {
      that.data.imgUrls[index] = fileUrlListResult[index].url;
    }
    var url = option.currentTarget.dataset.url;
    var imgUrls = that.data.imgUrls;
    wx.previewImage({
      current: url,
      urls: imgUrls
    });
  },
  //删除选择的抄送人
  delCopyUser: function (e) {

    var that = this;
    wx.showModal({
      content: '确定要删除吗？',
      success: function (sm) {
        if (sm.confirm) {
          // 用户点击了确定 可以调用删除方法了
          var userid = e.currentTarget.dataset.userid;
          var accountInfosList = that.data.accountInfosList;
          var userIds = that.data.userIds;
          //移除抄送人
          for (var i = 0; i < accountInfosList.length; i++) {
            var id = accountInfosList[i].id;
            if (id == userid) {
              accountInfosList.splice(i, 1);//从i的位置开始向后删除1个元素
              userIds.splice(i, 1);//从i的位置开始向后删除1个元素
            }
          }
          that.setData({
            accountInfosList: accountInfosList,
            userIds: userIds
          })
        } else if (sm.cancel) {
          console.log('用户点击取消')
        }
      }
    })

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  //提交保存
  formSubmit: function (e) {
    var userIds = this.data.userIds;
    if (userIds.length <= 0) {
      util.showMsg('请选择发送人！', 1, 'none');
      return;
    }
    //模板类型
    var template_type = this.data.types;
    var params = e.detail.value;

    var listFile = this.data.listFile;
    api.fetchApi2("logManage/saveLogsForMobile", {
      templateType: template_type,
      orgid: orgid,
      userId: userId,
      userName: userName,
      userIds: userIds,
      ...params,
      listFile: listFile,
    }, "POST").then(res => {
      if (res.data.code == 200) {
        util.showMsg("提交成功", 1, 'none');
        var pages = getCurrentPages(); // 当前页面
        var beforePage = pages[pages.length - 2]; // 前一个页面
        setTimeout(function () {
          wx.navigateBack({
            url: 'index',
            success: function () {
              beforePage.onLoad(); // 执行前一个页面的onLoad方法
            }
          });
        }, 1000);
      } else {
        util.showMsg(res.data.msg, 1, 'none');
      }
    });
  },
  redirectTo: function (e) {
    var that = this;
    var idx = e.currentTarget.id;
    if (idx == 0) {
      wx.navigateTo({
        url: 'write'
      });
    } else {
      wx.navigateTo({
        url: 'index'
      });
    }
  },
  //选择时间
  changeDate: function (e) {
    var that = this;
    var id = e.currentTarget.dataset.id;
    var val = e.detail.value;
    var STdate = that.data.STdate;
    STdate[id] = val;
    this.setData({
      STdate: STdate
    })
  },
  //用户选择
  userinfo: function (e) {
    wx.navigateTo({
      url: '../application/userinfo'
    });
  },
  //用户选择
  userinfo: function (e) {
    wx.navigateTo({
      url: '../application/userinfo?proId=""&appointType=""&processType=8&roleKey=""&examinealltype=""&searchusertype=copy'
    });
  },
  //类型选择
  typeselect: function (e) {
    var idx = e.currentTarget.dataset.id;
    this.setData({
      types: idx,
      show: true
    })
    //周报
    if (idx == 1) {
      this.setData({
        weekShow: true
      })
    }
    if (idx == 2) {
      this.setData({
        monthShow: true
      })
    }
    if (idx == 3) {
      this.setData({
        dayShow: true
      })
    }
  }

})